﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Windows.Forms;
using System.IO;

namespace SerialInput
{
    class Program
    {
        private static SerialPort port = new SerialPort("COM3",9600, Parity.None, 8, StopBits.One);
        private static string data;
        private static string filename;
        private static int count = 0;
        [STAThread]
         static void Main(string[] args)
        {
           Console.Write("Enter the text filename:");
           filename= Console.ReadLine();
           Console.WriteLine("Incoming Data:"); 
           port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived); 
           port.Open();
           Application.Run();
        }

         private static void port_DataReceived(object sender,SerialDataReceivedEventArgs e) 
         { // Show all the incoming data in the port's buffer 
             
             string reading = port.ReadExisting();
            // Console.WriteLine(reading);
             if (reading.Contains("S"))
             {
                 data += reading.Substring(1);
             }
             else if (reading.Contains("E"))
             {
                 data += reading.Substring(0, reading.Length - 1);
                 Console.WriteLine("Count: " + count++);
                 savedata(data); 
                 data = String.Empty;
             }
             else
             {
                 data += reading;
             }

         }

         private static void savedata(string data)
         {

             data = "NewData" + Environment.NewLine + data;
            try
             {
                 TextReader tr = new StreamReader(filename);
                 data = tr.ReadToEnd() + data;
                 tr.Close();
             }
             catch (FileNotFoundException)
             { }// do nothing if file not exist
             
             TextWriter tw = new StreamWriter(filename);
             tw.Write(data);
             tw.Close();
         }
    } 
}
